package com.cet.algorithm.二叉树.层级遍历;

import java.util.*;

/**
 * @program: algorithm
 * @description: 自底向上层级遍历
 * @author: 陈恩涛
 * @create: 2022-07-14 16:45
 **/
public class LC107 {

    public static void main(String[] args) {

    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        final List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            // 记录每层节点个数，进行遍历
            int len = queue.size();
            final List<Integer> list = new ArrayList<>();
            while (len > 0) {
                final TreeNode headerNode = queue.poll();
                list.add(headerNode.val);
                if (headerNode.left != null) {
                    queue.offer(headerNode.left);
                }
                if (headerNode.right != null) {
                    queue.offer(headerNode.right);
                }
                len--;
            }
            result.add(list);
        }
        Collections.reverse(result);
        return result;
    }
}
